%{
#include <stdio.h>
#include "ast_types.h"
#include "ll.h"
#include "llvm.h"
#include "y.tab.h"

int column=0; int lineno=0;

/* Function that counts the current column */
void count() {
  int i;
  for (i = 0; yytext[i] != '\0'; i++) {
    if (yytext[i] == '\n')
      column = 0;
    else if (yytext[i] == '\t')
      column += 8 - (column % 8);
    else
      column++;
  }
}
/* Function called in case of error during parsing */
void yyerror(char *s) {
  fprintf(stderr, "%s line %d col %d\n", s, lineno+1, column);
}

#define get_sval()                                                  \
    do {                                                            \
        char *res = malloc(sizeof(char) * (strlen(yytext) + 1));    \
        strcpy(res, yytext);                                        \
        yylval.sval = res;                                          \
    } while (0);                                                    \

#define get_sval_noquotes()                                         \
    do {                                                            \
        char *res = malloc(sizeof(char) * (strlen(yytext) - 1));    \
        strncpy(res, yytext + 1, strlen(yytext) - 2);               \
        yylval.sval = res;                                          \
    } while (0);                                                    \

%}
F ([0-9]+\.[0-9]*)
I ([0-9]+)
S (\"[^\n\"]*\")
ID ([$@]?[a-zA-Z_][a-zA-Z_0-9]*)
%%
"#"[^\n]* { count(); }
{F}      { count(); yylval.fval = atof(yytext); return(FLOAT); }
{I}      { count(); yylval.ival = atoi(yytext); return(INT); }
{S}      { count(); get_sval_noquotes(); return(STRING); }
"for"    { count(); return(FOR); }
"while"  { count(); return(WHILE);}
"if"     { count(); return(IF); }
"then"   { count(); return(THEN); }
"else"   { count(); return(ELSE); }
"return" { count(); return(RETURN); }
"class"  { count(); return(CLASS); }
"do"     { count(); return(DO); }
"def"    { count(); return(DEF); }
"in"     { count(); return(IN); }
"end"    { count(); return(END); }
"true"    { count(); return(LTRUE); }
"false"    { count(); return(LFALSE); }
".."	 { count(); return(TO); }
"<="	 { count(); return(LEQ); }
">="     { count(); return(GEQ); }
"=="	 { count(); return(EQ); }
"!="	 { count(); return(NEQ); }
"&&"     { count(); return(AND); }
"||"     { count(); return(OR); }
";"	 { count(); return(';'); }
","	 { count(); return(','); }
"."	 { count(); return('.'); }
"="      { count(); return('='); }
"("	 { count(); return('('); }
")"	 { count(); return(')'); }
"-"	 { count(); return('-'); }
"+"	 { count(); return('+'); }
"*"	 { count(); return('*'); }
"/"	 { count(); return('/'); }
"<"	 { count(); return('<'); }
">"	 { count(); return('>'); }

{ID}     { count(); get_sval(); return ID; }

"\n"     { count(); lineno++; return('\n'); }
[ \t\v\f]  { count(); }
.        ;
%%

